package cn.wolfcode.wolf2w.business.util;

import cn.wolfcode.wolf2w.business.ann.CurrentUser;
import cn.wolfcode.wolf2w.common.core.context.SecurityContextHolder;
import cn.wolfcode.wolf2w.member.api.domain.UserInfo;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

@Component
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {

    //springmvc在读取多个参数时，会调用该方法，验证当前参数是否符合要求，符合要求supportsParameter返回true，否则返回false
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        boolean b = parameter.getParameterType() == Long.class && parameter.hasParameterAnnotation(CurrentUser.class);
        return b;
    }

    //当supportsParameter返回true时，当前方法被调用，用于参数值的注入
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        Long userId = SecurityContextHolder.getUserId();
        return userId;
    }
}
